package org.abratuhi.kvngroupware.pubsub;

import java.util.ArrayList;
import java.util.List;

public class Hubnode<T> implements SubscriptionStorage<T>{
	
	String attributeId;
	Value<T> lowerBound;
	Value<T> upperBound;
	
	ArrayList<Subscription<T>> subscriptions = new ArrayList<Subscription<T>>();
	
	public Hubnode(String attrId, Value<T> min, Value<T> max){
		this.attributeId = attrId;
		setLowerBound(min);
		setUpperBound(max);
	}
	
	public void setLowerBound(Value<T> min){
		this.lowerBound = min;
	}
	
	public void setUpperBound(Value<T> max){
		this.upperBound = max;
	}
	
	public String getAttributeId(){
		return this.attributeId;
	}
	
	public Value<T> getLowerBound(){
		return this.lowerBound;
	}
	
	public Value<T> getUpperBound(){
		return this.upperBound;
	}
	
	public Range<T> getRange(){
		return new Range<T>(this.lowerBound, this.upperBound);
	}

	@Override
	public void addSubscription(Subscription<T> sub) {
		//if(sub.containsAttribute(attributeId))
			subscriptions.add(sub);
	}

	@Override
	public List<Subscription<T>> findMatchingSubscriptions(Publication<T> pub) {
		ArrayList<Subscription<T>> result = new ArrayList<Subscription<T>>();
		for(int i=0; i<subscriptions.size(); i++)
			if(subscriptions.get(i).matches(pub))
				result.add(subscriptions.get(i));
		return result;
	}

	@Override
	public List<Subscription<T>> findSubcriptions(String subscriberId) {
		ArrayList<Subscription<T>> result = new ArrayList<Subscription<T>>();
		for(int i=0; i<subscriptions.size(); i++)
			if(subscriptions.get(i).getSubscriberId().equals(subscriberId))
				result.add(subscriptions.get(i));
		return result;
	}

	@Override
	public void removeSubscription(Subscription<T> sub) {
		subscriptions.remove(sub);
	}

	@Override
	public void removeSubscriptions(String subscriberId) {
		for(int i=subscriptions.size()-1; i>=0; i--)
			if(subscriptions.get(i).getSubscriberId().equals(subscriberId)){
				subscriptions.remove(i);
			}
	}

	@Override
	public void updateSubscription(Subscription<T> sub) {
		subscriptions.set(subscriptions.indexOf(sub), sub);
	}
	
	public String toString(){
		return new String("Hubnode ["+getLowerBound().getValue().toString()+" <= "+attributeId+" <= "+getUpperBound().getValue().toString()+"]{"+subscriptions.size()+"}");
	}

}
